//
//  MoreBubbleViewController.m
//  KidReading
//
//  Created by telen on 15/12/7.
//  Copyright © 2015年 刘赞黄Telen. All rights reserved.
//

#import "MoreBubbleViewController.h"
#import "ConstDefine.h"

@interface BubbleBtn : UIView
+ (instancetype)bubbleBtn:(CGSize)size title:(NSString*)title;
+ (instancetype)bubbleBtn:(CGSize)size title:(NSString*)title titleOffset:(CGFloat)offset;
@property(nonatomic,assign)BOOL select;
@property(nonatomic,strong,readonly)UIButton* btn;
@property(nonatomic,weak)id delegate;
@property(nonatomic,assign)BOOL unline;
@end
@implementation BubbleBtn
{
    UILabel* titleLabel;
    UILabel* lineLabel;
}
@synthesize btn = overbtn;
+ (instancetype)bubbleBtn:(CGSize)size title:(NSString*)title titleOffset:(CGFloat)offset {
     return [[self alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height) title:title offset:offset];
}
+ (instancetype)bubbleBtn:(CGSize)size title:(NSString*)title
{
    return [[self alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height) title:title];
}

- (instancetype)initWithFrame:(CGRect)frame title:(NSString*)title offset:(CGFloat)offset {
    if (self = [super initWithFrame:frame]) {
        titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(offset, 0, frame.size.width, frame.size.height)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.text = title;
        titleLabel.font = [UIFont systemFontOfSize:frame.size.height*0.4];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        titleLabel.textColor = [UIColor blackColor];
        [self addSubview:titleLabel];
        //
        lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, frame.size.height-1, frame.size.width-20, 1)];
        lineLabel.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
        [self addSubview:lineLabel];
        _unline = YES;
        //
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = self.frame;
        [self addSubview:btn];
        [btn addTarget:self action:@selector(_down:) forControlEvents:UIControlEventTouchDown];
        [btn addTarget:self action:@selector(_up:) forControlEvents:UIControlEventTouchUpInside];
        [btn addTarget:self action:@selector(_up:) forControlEvents:UIControlEventTouchUpOutside];
        [btn addTarget:self action:@selector(_up:) forControlEvents:UIControlEventTouchCancel];
        overbtn = btn;
        //
        self.select = NO;
    }
    return self;

}

- (instancetype)initWithFrame:(CGRect)frame title:(NSString*)title
{
    return [self initWithFrame:frame title:title offset:20];
}

- (void)setUnline:(BOOL)unline
{
    _unline = unline;
    lineLabel.hidden = !unline;
}

- (void)setSelect:(BOOL)select
{
    _select = select;
    if (select) {
        self.backgroundColor = [UIColor colorWithHexString:@"#b2b9eb"];
        titleLabel.textColor = [UIColor whiteColor];
        overbtn.enabled = NO;
    }else{
        self.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor blackColor];
        overbtn.enabled = YES;
    }
}

- (void)_down:(UIButton*)btn
{
    UIView* view = self;
    [UIView animateWithDuration:0.1 animations:^{
        view.transform = CGAffineTransformMakeScale(1.05, 1.05);
    }];
}

- (void)_up:(UIButton*)btn
{
    UIView* view = self;
    [UIView animateWithDuration:0.1 delay:0.1 options:0 animations:^{
        view.transform = CGAffineTransformMakeScale(1, 1);
    } completion:nil];
}

@end

@interface MoreBubbleViewController ()
{
    TLBubbleView* bubbleView;
}
@end

@implementation MoreBubbleViewController

- (void)viewDidLoad {
    self.title = nil;
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.05];
    //
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_tapEmpty)];
    [self.view addGestureRecognizer:tap];
    //
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(_tapEmpty)];
    [self.view addGestureRecognizer:panGR];
}

- (void)_tapEmpty
{
    CGPoint pt = bubbleView.center;
    pt.y -= bubbleView.frame.size.height*0.5;
    [UIView animateWithDuration:0.3f animations:^{
        bubbleView.center = pt;
        bubbleView.transform = CGAffineTransformMakeScale(1, 0.000001);
    } completion:^(BOOL finished) {
        [self.view removeFromSuperview];
        [self willMoveToParentViewController:nil];
        [self removeFromParentViewController];
    }];
}
- (void)undo{}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showBubbleViewSelfDefineToVC:(UIViewController *)vc {
    CGFloat ratio = [DataProcessing shareSingle].ratio_w;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        ratio /= 1.28;
    }
    CGFloat w = 220/ratio;
    if (self.itemWidth) {
        w = self.itemWidth/ratio;
    }
    CGFloat h_one = 50/ratio;
    if (self.itemHeight) {
        h_one = self.itemHeight/ratio;
    }
    CGFloat radius = 12/ratio;
    if (self.radius) {
        radius = self.radius/ratio;
    }
    CGFloat arrowHeight = 12/ratio;
    if (self.arrorHeight) {
        arrowHeight = self.arrorHeight/ratio;
    }
    //
    [vc addChildViewController:self];
    [vc.view addSubview:self.view];
    CGPoint pt = self.view.center;
    if (_followView) {
        pt = [_followView.superview convertPoint:_followView.center toView:self.view];
        if (self.yRate) {
            pt.y += _followView.frame.size.height*self.yRate;
        }else {
           pt.y += _followView.frame.size.height*0.86;
        }
    }
    if (!bubbleView && _orderByArr.count > 0) {
        CGSize maxSize = CGSizeMake(w,h_one*_orderByArr.count+arrowHeight+radius*2);
        for (int i=0; i<_orderByArr.count; i++) {
            NSString *nameEn = [_orderByArr[i] valueForKey:@"nameEn"];
            NSString *nameCh = [_orderByArr[i] valueForKey:@"nameZh"];
            NSString *title = [DataProcessing chooseLanguageFromCN:nameCh andEN:nameEn];
            CGSize tSize = [title sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:h_one*0.4]}];
            tSize.width+=(h_one*0.4)*2;
            if (tSize.width>maxSize.width) {
                maxSize = CGSizeMake(tSize.width, maxSize.height);
            }
        }
        bubbleView = [TLBubbleView TLBubbleViewWithSize:maxSize];
        [self.view addSubview:bubbleView];
        //
        for (int i=0; i<_orderByArr.count; i++) {
            //NSString* title = nil;
            MoreBooksOrderType tag;
            NSString *nameEn = [_orderByArr[i] valueForKey:@"nameEn"];
            NSString *nameCh = [_orderByArr[i] valueForKey:@"nameZh"];
            NSString *title = [DataProcessing chooseLanguageFromCN:nameCh andEN:nameEn];
            BOOL isCurrent = [[_orderByArr[i] valueForKey:@"isCurrent"] integerValue];
            //title = (NSString *)_orderByArr[i];
            tag = i + 1;
            CGSize size = CGSizeMake(maxSize.width, h_one);
            size.width -= 0;
            BubbleBtn* bbtn = [BubbleBtn bubbleBtn:size title:title titleOffset:10];
            [bubbleView.contentView addSubview:bbtn];
            bbtn.center = CGPointMake(maxSize.width*0.5, h_one*(0.5+i)+radius);
            bbtn.btn.tag = tag;
            if (isCurrent) {
                bbtn.select = YES;
            }
            [bbtn.btn addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
            if (i+1 == _orderByArr.count) {
                bbtn.unline = NO;
            }else{
                bbtn.unline = YES;
            }
        }
        //
        [bubbleView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(undo)]];
        //
        bubbleView.radius = radius;
        bubbleView.borderWidth = 4/ratio;
        bubbleView.arrowHeight = arrowHeight;
        CGFloat angle = M_PI/6;
        if (self.arrorAngle) {
            angle = self.arrorAngle;
        }
        bubbleView.arrowAngle = angle;
        bubbleView.arrowDirectorType = TLBubbleArrowType_Top;
        bubbleView.arrowLineRatio = 1-(16/ratio/maxSize.width);
        bubbleView.backgroundColor = [UIColor whiteColor];
        bubbleView.pt_Arrow = pt;
        bubbleView.borderColor = [UIColor colorWithHexString:@"b2b9eb"];
        [bubbleView displayMask];
        //
        pt = bubbleView.center;
        bubbleView.center = CGPointMake(pt.x, pt.y-bubbleView.frame.size.height*0.5);
        bubbleView.transform = CGAffineTransformMakeScale(1, 0.000001);
        [UIView animateWithDuration:0.2f animations:^{
            bubbleView.center = pt;
            bubbleView.transform = CGAffineTransformMakeScale(1, 1);
        }];
    }

}

- (void)showBubbleViewToVC:(UIViewController *)vc
{
    CGFloat ratio = [DataProcessing shareSingle].ratio_w;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        ratio /= 1.28;
    }
    CGFloat w = 190/ratio;
    CGFloat h_one = 50/ratio;
    CGFloat radius = 12/ratio;
    CGFloat arrowHeight = 12/ratio;
    //
    [vc addChildViewController:self];
    [vc.view addSubview:self.view];
    CGPoint pt = self.view.center;
    if (_followView) {
        pt = [_followView.superview convertPoint:_followView.center toView:self.view];
        pt.y += _followView.frame.size.height*0.86;
    }
    if (!bubbleView && _orderByArr.count > 0) {
        bubbleView = [TLBubbleView TLBubbleViewWithSize:CGSizeMake(w,h_one*_orderByArr.count+arrowHeight+radius*2)];
        [self.view addSubview:bubbleView];
        //
        for (int i=0; i<_orderByArr.count; i++) {
            NSString* title = nil;
            MoreBooksOrderType tag;
            if ([_orderByArr[i] isKindOfClass:[NSString class]]) {
                title = (NSString *)_orderByArr[i];
                tag = i + 1;
            }else {
                NSNumber* num = _orderByArr[i];
                tag = [num integerValue];
                switch (tag) {
                    case MoreBooksOrderType_abc:
                        title = NSLocalizedString(@"alphabetical", nil);
                        break;
                    case MoreBooksOrderType_popular:
                        title = NSLocalizedString(@"popular", nil);
                        break;
                    case MoreBooksOrderType_new:
                        title = NSLocalizedString(@"new", nil);
                        break;
                    case MoreBooksOrderType_favoritetime:
                        title = NSLocalizedString(@"addlasttime", nil);
                        break;
                    case MoreBooksOrderType_readingtime:
                        title = NSLocalizedString(@"readinglasttime", nil);
                        break;
                    case MoreBooksOrderType_none:
                        title = @"Default";
                        break;
                    case MoreBooksOrderType_bookIds:
                        title = NSLocalizedString(@"defaultorder", nil);;
                        break;
                    default:
                        title = @" ^ v ^ ";
                        break;
                }
            }
            
            CGSize size = CGSizeMake(w, h_one);
            size.width -= 2;
            BubbleBtn* bbtn = [BubbleBtn bubbleBtn:size title:title];
            [bubbleView.contentView addSubview:bbtn];
            bbtn.center = CGPointMake(w*0.5, h_one*(0.5+i)+radius);
            bbtn.btn.tag = tag;
            if (_currentOrderType == tag) {
                bbtn.select = YES;
            }
            [bbtn.btn addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
            if (i+1 == _orderByArr.count) {
                bbtn.unline = NO;
            }else{
                bbtn.unline = YES;
            }
        }
        //
        [bubbleView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(undo)]];
        //
        bubbleView.radius = radius;
        bubbleView.borderWidth = 4/ratio;
        bubbleView.arrowHeight = arrowHeight;
        bubbleView.arrowAngle = M_PI/6;
        bubbleView.arrowDirectorType = TLBubbleArrowType_Top;
        bubbleView.arrowLineRatio = 0.9;
        bubbleView.backgroundColor = [UIColor whiteColor];
        bubbleView.pt_Arrow = pt;
        bubbleView.borderColor = [UIColor colorWithHexString:@"b2b9eb"];
        [bubbleView displayMask];
        //
        pt = bubbleView.center;
        bubbleView.center = CGPointMake(pt.x, pt.y-bubbleView.frame.size.height*0.5);
        bubbleView.transform = CGAffineTransformMakeScale(1, 0.000001);
        [UIView animateWithDuration:0.2f animations:^{
            bubbleView.center = pt;
            bubbleView.transform = CGAffineTransformMakeScale(1, 1);
        }];
    }
}

- (void)clicked:(UIButton*)btn
{
    if (_delegate && [_delegate respondsToSelector:@selector(moreBubbleViewController_select:)]) {
        [_delegate moreBubbleViewController_select:btn.tag];
    }
    [self _tapEmpty];
}

@end
